my $file1=$ARGV[0];
my $file2=$ARGV[1];
my $distance=$ARGV[2];
open(FH,"<$file1") or die;
my @in1=<FH>;
chomp(@in1);
close(FH);
open(FH,"<$file2") or die;
my @in2=<FH>;
chomp(@in2);
close(FH);
my $count=0;
my $imprint_count=0;
#my $i=0;

foreach my $line1(@in1){
#	if($i==0){
#		$i++;
#		next;
#	}
	my @splitin1=split "\t",$line1;
	next if $splitin1[0] eq "chrX" or $splitin1[0] eq "chrY" or $splitin1[0] eq "chrM";
#	my $j=0;
	my $start=$splitin1[1]-$distance;
	my $end=$splitin1[2]+$distance;
	foreach my $line2(@in2){
#		if($j==0){
 #               	$j++;
#                	next;
 #       	}	
		my @splitin2=split "\t",$line2;
		next if $splitin2[0] eq "chrX" or $splitin2[0] eq "chrY" or $splitin2[0] eq "chrM";
		if(($splitin1[0] eq $splitin2[0]) &&( ($start <= $splitin2[3] && $end >= $splitin2[4]) || ($end <= $splitin2[4] && $end >= $splitin2[3]) || ($start <= $splitin2[4] && $start >= $splitin2[3]))){
			$imprint_count++;
			print("$splitin1[3]\n");
			last;
		}
	}	
}

foreach my $line2(@in2){
#	if($i==0){
#		$i++;
#		next;
#	}
	my @splitin2=split "\t",$line2;
	next if $splitin2[0] eq "chrX" or $splitin2[0] eq "chrY" or $splitin2[0] eq "chrM";
#	my $j=0;
	my $start=$splitin2[3]-$distance;
	my $end=$splitin2[4]+$distance;
	foreach my $line1(@in1){
#		if($j==0){
 #               	$j++;
#                	next;
 #       	}	
		my @splitin1=split "\t",$line1;
		next if $splitin1[0] eq "chrX" or $splitin1[0] eq "chrY" or $splitin1[0] eq "chrM";
		if(($splitin2[0] eq $splitin1[0]) &&( ($start <= $splitin1[1] && $end >= $splitin1[2]) || ($end <= $splitin1[2] && $end >= $splitin1[1]) || ($start <= $splitin1[2] && $start >= $splitin1[1]))){
			$count++;
			last;
		}
	}	
}

print "Imprint gene overlap count is: $imprint_count\nASM count is: $count\n";
